<template>
  <BasicModal v-bind="$attrs" @register="register" showFooter :title="getTitle" width="70%" @ok="handleSubmit"
    :show-ok-btn="!wait && !approveAfterData.approveNo" :confirm-loading="loading" okText="发起审批"
    :ok-button-props="{ loading }" @cancel="cancelFn">

    <!-- 审批进度 @cancel="applyViewClose" @cancel="cancelFn" -->
    <div style="width: 100%; height: 100%">
      <div style="margin-left: 15px;" v-if="approveAfterData.approveNo">
        提交成功审批单号: <span style="color: green;">{{ approveAfterData.approveNo }}</span>可前往‘钟部经理抽成审批列表’查看
      </div>
      <!--      <div style="margin-left: 15px;" v-if="dataJson.id">-->
      <!--        <div v-if="dataJson.approveNo">-->
      <!--          提交成功审批单号: <span style="color: green;"> {{ dataJson.approveNo }}</span> 可前往‘业务员抽成审批列表’查看-->

      <!--        </div>-->

      <!--      </div>-->
      <!-- v-on="gridEvents" overflow: hidden -->
      <div style="height: 450px;">
        <vxe-grid ref="tableRef" v-bind="gridOptions">
          <template #toolbar_buttons>

          </template>
          <template #footer_orderCommissionPrice>
            <span style="color: red;">{{ totalObj.orderCommissionPrice }}{{ totalObj.orderCommissionPrice ? '元' : ''
              }}</span>
          </template>

          <template #action="{ row }">
            <TableAction outside :actions="createActions(row)" />
          </template>
        </vxe-grid>
      </div>


      <Modal v-model:visible="applyViewShow" title="审批详情" @ok="subFn" :okButtonProps="{ loading, title: '关闭' }"
        @cancel="applyViewClose">
        <div>
          <div style="margin-bottom: 5px;">审批详情:</div>
          <Timeline>
            <TimelineItem v-for="(item, index) in startNodeList" :key="index">
              <div style="display: flex;">
                <div>{{ item.userName }}</div>
                <div style="margin-left: 3px">{{ item.approverType == 1 ? '审批人' : '知会人' }}</div>



              </div>

            </TimelineItem>
          </Timeline>
        </div>
      </Modal>
      <Modal v-model:visible="visible" title="提示信息" @ok="handleOk">
        <p v-for="(item, index) in msgList">{{ item }}</p>
      </Modal>
    </div>
    <template #centerFooter>
      <!-- <Button :loading="loading" @click="saveOrderNoStorageFn" v-if="!dataJson.id">暂存</Button> -->
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref, h, toRaw, reactive, onMounted } from 'vue';

import {
  BasicTableProps,
  VxeGridInstance
} from '@/components/VxeTable';
import {
  confirmColumns,
  checkboxCountFn
} from './role.data';

import { BasicModal, useModalInner } from '@/components/Modal';
import { useLocaleStore } from '@/store/modules/locale';

import { BasicTree, TreeItem } from '@/components/Tree';
import { saveOrderNoStorage, removeOrderNoStorage, getOrderNoStorageList } from '@/api/heng/ywManage';
import { ywApprovalCreateView, ywZhongBuSubmit } from '@/api/sys/approval';


import { TableAction, ActionItem } from '@/components/Table';

import { Modal, Timeline, TimelineItem, Button, Spin } from 'ant-design-vue';

import { useMessage } from "@/hooks/web/useMessage";
import util from '@/utils/util';
const emit = defineEmits(['success', 'register']);
const wait = ref(false);
const { createMessage } = useMessage();
const localeStore = useLocaleStore();

const applyViewShow = ref(false);
const visible = ref(false);
const msgList = ref([]);
const visible2 = ref(false);

var openNum = 0;

const tableRef = ref<VxeGridInstance>();

const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: confirmColumns,
  filterConfig: {
    remote: true,
  },
  exportConfig: {},

  showFooter: true,
  footerData: [
    { approveNo: '合计' }
  ],
  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
    refresh: true,
  },

  pagerConfig: {
    enabled: false
  },

});



const startNodeList = ref([]);
const loading = ref(false);
const loading2 = ref(false);

const dataList = ref({});
const totalObj = ref({});
const storageList = ref([]);
const dataJson = ref({ id: "", approveNo: "" });

const approveAfterData = ref({ approveNo: "" });//审批后返回的数据

const type = ref("");
const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //打开弹层后的回调
  // resetFields();
  setModalProps({ confirmLoading: false });
  let arr = data.selectList;
  dataList.value = data.selectList;
  wait.value = data.wait;
  type.value = data.type;
  approveAfterData.value.approveNo = "";

  // tableRef.value?.reloadData(data.selectList);
  loading.value = false;
  loading2.value = true;
  msgList.value = [];
  storageList.value = [];

  tableRef.value?.reloadData(arr);
  totalObj.value = checkboxCountFn(arr);
  gridOptions.footerData = [{ approveNo: "合计:" + arr.length + "条" }];

});

const getTitle = computed(() => ('确认提交钟部经理抽成审批？'));


function applyViewOpen() {
  if (msgList.value.length) {
    createMessage.error(msgList.value[0]);
    return;
  }

  applyViewShow.value = true;
}

function applyViewClose() {
  applyViewShow.value = false;
}





const handleSubmit = () => {
  loading.value = true;

  ywApprovalCreateViewFn()


}



function ywApprovalCreateViewFn() {
  ywApprovalCreateView({ approvalName: "钟部经理提成审批" }).then(res => {
    loading.value = false;

    if (res.code == 200) {
      startNodeList.value = res.data.nodes;
      applyViewOpen();


    } else {
      createMessage.error(res.message);

    }

  })
}


function subFn() {
  try {
    let tableList = tableRef.value?.getFullData();
    if (tableList?.length == 0) {
      createMessage.error("暂无数据!");
      return;
    }
    // console.log(tableList);
    let list = util.copy(unref(tableList));
    let dJson = { list, type: type.value };
    msgList.value = [];
    loading.value = true;
    ywZhongBuSubmit(dJson).then(res => {
      if (res.code == 200) {
        if (res.data.errorMsg) {
          msgList.value = res.data.errorMsg;
          visible.value = true;
        } else {
          approveAfterData.value = res.data;
          sunccFn(res);

        }
      } else {
        createMessage.error(res.message);
      }
    }).finally(() => {
      loading.value = false;
      setModalProps({ confirmLoading: false });
    })
  } catch (e) {
    console.log(e)
  }
}


function sunccFn(result) {
  if (result && result.code == 200) {
    applyViewClose();
    createMessage.success("审批提起成功");
    emit('success');
  } else {
    createMessage.error(result.message);
  }

}
function cancelFn() {
  openNum = 1;
  closeModal()
  emit('success');

}

function handleOk() {
  visible.value = false;
}
function openWaitList() {
  visible2.value = true;
}


const createActions = (record) => {
  let actions: ActionItem[] = [
  ];
  if (record.storageType) {
    actions.push(
      {
        label: '删除暂存',
        color: 'error',
        popConfirm: {
          title: '是否确认删除',
          confirm: () => {
            handleDelete(record)
          },
        },
      },
    )
  }

  return actions;
};


/**
 * 
 * @param record 删除暂存
 */
function handleDelete(record: Recordable) {
  removeOrderNoStorage({ orderNo: record.orderNo }).then(res => {
    if (res && res.code == 200) {
      createMessage.success(res.message);
      emit('success');
      getOrderNoStorageListFn();
    } else {
      createMessage.error(res.message);
    }
  })
}

function getOrderNoStorageListFn() {
  getOrderNoStorageList({ type: type.value }).then(res => {
    if (res && res.code == 200) {
      storageList.value = res.data ? res.data : [];
      let arr = []
      if (!wait.value) {
        arr = [...dataList.value, ...storageList.value]
      } else {
        arr = [...dataList.value];

      }
      tableRef.value?.reloadData(arr);
      totalObj.value = checkboxCountFn(arr);
      gridOptions.footerData = [{ approveNo: "合计:" + arr.length + "条" }];
    } else {
      createMessage.error(res.message);
    }
  })
}






</script>
<style lang="less">
.item-row {
  margin: 0 auto;

  //padding-left: 5%;
  .ant-form-item-label {
    flex: 0 0 28.5%;
    max-width: 28.5%;
  }
}

.lqfp-8 {
  //padding-left: 9% !important;

}

.table-header-btn {
  padding-left: 10px;
  color: gray;
  font-size: 12px;
  cursor: pointer;
}
</style>
